<template>
  <h1>购物车</h1>
  <ul>
    <li v-for="el,index in arr">
      <img :src="el.pic" alt="">
      {{ el.name }} - {{ el.price }}
      <button @click="onReduce(el,index)">-</button>
      <input type="text" v-model="el.num">
      <button @click="el.num++">+</button>
      <button @click="onDel(index)">x</button>
    </li>
  </ul>
  <h1>总计：{{total}}元</h1>
</template>

<script setup>
import { computed, ref } from 'vue';
//数据源
const arr = ref([
  {pic:'/imgs/TCL彩电.png',name:'TCL彩电',price:1000,num:1},
  {pic:'/imgs/机顶盒.png',name:'机顶盒',price:50,num:1},
  {pic:'/imgs/PPTV电视.png',name:'PPTV电视',price:3000,num:1}
])
// 总价格
const total = computed(()=>{
  let _total = 0;
  arr.value.forEach(el=>_total += el.num*el.price);
  return _total;
})
// 删除
const onDel = index=>{
  if(confirm('确定删除吗？')){
    arr.value.splice(index,1);
  }
}
//减少
const onReduce = (el,index)=>{
  if(el.num==1){
    //最后一个，弹框提醒
    if(confirm('确定删除吗？')){
      arr.value.splice(index,1);
    }
  }else{
    //不是最后一个
    el.num--;
  }
  

}
// el.num--
</script>

<style scoped>
input{width: 40px;text-align: center;}
</style>